<template>
	<view class="app-components-goods-layout-form-popup" v-if="formData">
		<view class="e-flex e-flex-between" @tap="formPopupShow = true">
			<text class="fw-500">{{ formData.form.title }}{{ replyInfo || showStatus ? '' : `  (${$t('user.orderGoodsFormTxt3')})` }}</text>
			<view class="fw-500 e-flex">
				<text class="e-p-r-10" v-if="showStatus">{{ $t(hasEdit ? 'common.alreadyFilled' : 'common.noFilled') }}</text>
				<text class="e-p-r-10 white-nowrap" :class="priceClass" v-else>{{ global.unitEn }}{{ priceFormat(formData.subFormDto.totalPrice || 0, 2) }}</text>
				<app-image src="arrow_right.png" :size="['28rpx']" />
			</view>
		</view>
		<layout-form-popup
			ref="layoutFormPopupRef"
			v-model:value="formPopupShow"
			:formData="formData"
			:price="price"
			:number="number"
			:subType="subType"
			:disabled="disabled"
			@updatePrice="handleUpdatePrice"
			@edit="handleEditGoodsForm"
		/>
	</view>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { CardFormData, GoodsForm } from '@/common/request/api';
import type { LayoutFormModelValue,LayoutFormPopupInstance } from '@/typings';
import { priceFormat } from '@/common/utils';

const props = withDefaults(
	defineProps<{
		formJson?: string;
		info?: {
			form: GoodsForm;
			proId: string;
			skuId: string;
		};
		replyInfo?: boolean;
		showStatus?: boolean;
		price: number;
		number: number;
		subType: 0 | 1 | 2;
		disabled?: boolean;
		priceClass?:string
	}>(),
	{
		priceClass:'c-red'
	}
);
const emit = defineEmits(['edit']);

const formPopupShow = ref(false);
const formData = ref<CardFormData | undefined>();

const getFormData = () => {
	if (props.formJson) {
		formData.value = JSON.parse(props.formJson);
	} else if (props.info) {
		formData.value = {
			formId: props.info.form.id,
			form: props.info.form,
			subFormDto: {
				formId: props.info.form.id,
				proId: props.info.proId,
				proPrice: props.price,
				proSize: props.number,
				skuId: props.info.skuId,
				subType: props.subType,
				totalPrice: 0,
				list: []
			}
		};
	} else {
		formData.value = undefined;
	}
};

watch(
	() => props.formJson,
	() => {
		getFormData();
	},
	{
		immediate: true
	}
);

watch(
	() => props.info,
	() => {
		getFormData();
	},
	{
		immediate: true
	}
);

const handleUpdatePrice = (value: number) => {
	formData.value!.subFormDto.totalPrice = value;
};
const hasEdit = ref(false);
const handleEditGoodsForm = (value: LayoutFormModelValue) => {
	hasEdit.value = true;
	emit('edit', value);
};

const layoutFormPopupRef = ref<LayoutFormPopupInstance>();
const handleSubmitGoodsForm = async (subType: 0 | 1 | 2) => {
	await layoutFormPopupRef.value?.submitGoodsForm?.(subType);
};

defineExpose({
	submitGoodsForm: handleSubmitGoodsForm
});
</script>

<style lang="scss" scoped>
@include appBem_b(components-goods-layout-form-popup) {
	
}
</style>
